package com.hean.entity;

import java.util.ArrayList;
import java.util.List;

public class Worm {
	public static final int D_UP = 1;
	public static final int D_DOWN = -1;
	public static final int D_LEFT = 2;
	public static final int D_RIGHT = -2;

	private List<Cell> cells = new ArrayList<Cell>();

	private int direction = Worm.D_DOWN;

	private int maxCellX;
	private int maxCellY;

	public Worm(int length, Cell head, int maxCellX, int maxCellY) {
		cells.add(head);
		for (int i = 1; i < length; i++) {
			Cell cell = new Cell(head.x + i, head.y);
			cells.add(cell);
		}
		this.maxCellX = maxCellX;
		this.maxCellY = maxCellY;
	}

	/**
	 * 
	 */
	public void step() {
		Cell newHead = new Cell(getHead());
		switch (direction) {
		case D_UP:
			newHead.y--;
			break;
		case D_DOWN:
			newHead.y++;
			break;
		case D_LEFT:
			newHead.x--;
			break;
		case D_RIGHT:
			newHead.x++;
		}
		if (validateCell(newHead)) {
			cells.add(0, newHead);
			cells.remove(cells.size() - 1);
		}
	}

	/**
	 * 
	 * @param newDirection
	 * @return
	 */
	public boolean changeDirection(int newDirection) {
		if (direction + newDirection != 0) {
			this.direction = newDirection;
			return true;
		}
		return false;
	}

	public boolean validateCell(Cell cell) {
		if (cell.x >= 0 && cell.x < maxCellX && cell.y >= 0
				&& cell.y < maxCellY && !cells.contains(cell)) {
			return true;
		}
		return false;
	}

	public List<Cell> getCells() {
		return cells;
	}

	public Cell getHead() {
		return cells.get(0);
	}

	public int getLength() {
		return cells.size();
	}

	public int getDirection() {
		return direction;
	}

	public void setDirection(int direction) {
		this.direction = direction;
	}

	public int getMaxCellX() {
		return maxCellX;
	}

	public int getMaxCellY() {
		return maxCellY;
	}

}
